package com.ymatou.iapi.optrade.testcase;

import java.math.BigDecimal;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.req.RollbackToWaitDeliveryReq;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.RollbackToWaitDeliveryCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceOrderCallService;
import com.ymttest.database.sharding.db.sharding.model.AutoReceiveOptDetailPo;
import com.ymttest.database.sharding.db.sharding.model.AutoReceiveOptPo;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sharding.model.OrderStatusLogPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.utils.TestDataManager;
/**
*订单回滚到待发货接口
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_RollbackToWaitDelivery {
	private static RollbackToWaitDeliveryReq rollbackToWaitDeliveryReq;
	private static RollbackToWaitDeliveryCall rollbacktowaitdeliveryCall;
	
	private static OrderShardingWapper orderShardingWapper = new OrderShardingWapper();

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("订单回滚到待发货接口");
	}

	@Before
	public void caseUp() {
		rollbackToWaitDeliveryReq = new RollbackToWaitDeliveryReq();
		rollbacktowaitdeliveryCall = new RollbackToWaitDeliveryCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(rollbacktowaitdeliveryCall.getOpurl());
		orderShardingWapper.activeDeadCommunicationsLink(orderShardingWapper);
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	/*	
	 * 	 贝海面单已签收 和 已删除 数据sql
	 * 
	 * -- 已签收
		select * from ymtlogistics.logistics_info x
		inner join ymtlogistics.logistics_detail y on x.id = y.info_id 
		where y.ymt_status = 3 and y.deleted = 0;

		-- 已删除
		select * from ymtlogistics.logistics_info x
		inner join ymtlogistics.logistics_detail y on x.id = y.info_id 
		where y.ymt_status = -3 and y.deleted = 0;
		
		*
		*
		*/

//	/*
//	 * 修改数据，逻辑 删除码头物流运单数据
//	 * */
//	private static void onXloboBillDeletedCall(String billNo)
//			throws ClientProtocolException, IOException {
//
//		new DefaultWapper()
//				.executeUpdateSql(String
//						.format("UPDATE Ymt_BillCodeSummary SET IsDeleted=1,UpdateTime=GETDATE() where billCode = '%s' and IsDeleted=0",
//								billNo));
//
//	}

	/**
	 * 校验订单表状态，单主状态操作日志表
	 */
	public static void verifyOrderStatus(long orderId, String operateUser,
			String reason) {

		
		// 订单表(order)
		OrderPo ymtOrders = orderShardingWapper.selectOrderbyOrderId(orderId);

		Logger.comment(String.format("验证订单表(order)表 orderId: %s", orderId));

		Logger.verifyEquals(17, ymtOrders.getOrderStatus(), "验证orderStatus");

		//订单主状态操作日志表(order_status_log)
		OrderStatusLogPo orderStatusLogPo = orderShardingWapper
				.selectOrderStatusLogByOrderId(orderId);

		Logger.comment("验证订单主状态操作日志表(order_status_log)");

		Logger.verifyEquals(
				String.format("订单回滚到待发货(%s,%s)", operateUser, reason),
				orderStatusLogPo.getMemo(), "验证数据库Memo");
		Logger.verifyEquals(17, orderStatusLogPo.getOrderStatus(),
				"验证数据库OrderStatus");

		Logger.verifyEquals(true,
				Utils.calcTimeSpanMin(orderStatusLogPo.getAddTime()) < 2,
				"验证数据库AddTime跟系统当前时间差为2分钟内");

		Logger.verifyEquals(orderId, orderStatusLogPo.getOrderId(),
				"验证数据库OrderId");
		Logger.verifyEquals(-1L, orderStatusLogPo.getOperator(),
				"验证数据库Operator");

		AutoReceiveOptPo autoReceiveOptPo = orderShardingWapper
				.selectAutoReceiveOptByOrderId(orderId);

		Logger.verifyEquals(null, autoReceiveOptPo, String.format(
				"验证自动确认收货时间操作表（auto_receive_opt）  orderId: %s 记录已删除", orderId));

		AutoReceiveOptDetailPo actual = orderShardingWapper
				.selectAutoReceiveOptDetailByOrderId(orderId);

		Logger.verifyEquals(null, actual, String.format(
				"验证自动确认收货时间操作表（auto_receive_opt_detail）  orderId: %s 记录已删除",
				orderId));

	}
	@Test
	@Category({P1.class})
	@TestCase
	//@Ignore
	//（需要贝海发货，忽略）
	public void Tc_RollbackToWaitDelivery_001() {
		Logger.start(true, "订单回滚到待发货成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeOrderWithLuxury(false);
			
			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

			long userId = placeOrderResp.getUserId();

			long tradingId = placeOrderResp.getTradingId();
			
			BigDecimal useAccountAmount = placeOrderResp.getPayableAmount();
			
			TradingCallService.payOrder(userId, useAccountAmount, tradingId);

			TradingCallService.sellerAcceptOrder(sellerId, orderId);
			TradingCallService.delivery(sellerId, orderId, LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);

			Logger.comment("前置数据准备结束");
			
			Thread.sleep(5000);

			String operateUser = "sys";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("200",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("0",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals(true, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

			// 订单主表
			verifyOrderStatus(orderId,
					rollbackToWaitDeliveryReq.getOperateUser(),
					rollbackToWaitDeliveryReq.getReason());

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_RollbackToWaitDelivery_002() {
		Logger.start(true, "订单号不存在");
		try {
			Integer orderId = 1111111;

			String operateUser = "sys";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("201",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("101",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals(false, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_RollbackToWaitDelivery_003() {
		Logger.start(true, "订单号为null");
		try {

			String operateUser = "sys";
			String reason = "autotest rollback";

			//rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("400",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("100",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals("orderId:订单号未提供",
					rollbacktowaitdeliveryCall.getString("msg"), "验证msg");
			Logger.verifyEquals(false, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_RollbackToWaitDelivery_004() {
		Logger.start(true, "操作人为null");
		try {
			Integer orderId = 1111111;

			//String operateUser="autotest";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			//rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("400",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("100",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals("operateUser:操作人未提供",
					rollbacktowaitdeliveryCall.getString("msg"), "验证msg");
			Logger.verifyEquals(false, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_RollbackToWaitDelivery_005() {
		Logger.start(true, "订单状态不是已发货状态");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingCallService
					.orderAccept();

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

			Logger.comment("前置数据准备结束");

			String operateUser = "sys";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("201",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("102",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals("当前订单" + orderId + "状态不匹配",
					rollbacktowaitdeliveryCall.getString("msg"), "验证msg");
			Logger.verifyEquals(false, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_RollbackToWaitDelivery_006() {
		Logger.start(true, "订单不是用贝海发货");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingCallService
					.orderAccept();

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			TradingCallService.delivery(sellerId, orderId, false);

			Logger.comment("前置数据准备结束");

			String operateUser = "sys";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("201",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("115",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals("当前订单" + orderId + "非贝海发货",
					rollbacktowaitdeliveryCall.getString("msg"), "验证msg");
			Logger.verifyEquals(false, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_RollbackToWaitDelivery_007() {
		Logger.start(true, "该订单码头没有运单号记录");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingCallService
					.orderDelivery();

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

			Logger.comment("前置数据准备结束");

			String operateUser = "sys";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("201",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("116",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals("当前订单" + orderId + "没有运单号",
					rollbacktowaitdeliveryCall.getString("msg"), "验证msg");
			Logger.verifyEquals(false, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	@Ignore
	public void Tc_RollbackToWaitDelivery_008() {
		Logger.start(true, "订单有多个物流单号,所有面单都已删除,订单回滚成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingCallService
					.orderDelivery();

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			String billNo2 = "DB503225847US";

			TradingCallService.saveDeliverSummary(orderId, sellerId, billNo2);

			Logger.comment("前置数据准备结束");

			String operateUser = "auto";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("200",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");

			verifyOrderStatus(orderId, operateUser, reason);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_RollbackToWaitDelivery_009() {
		Logger.start(true, "订单有多个物流单号,其中有贝海未删除运单,订单回滚失败");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingCallService
					.orderDelivery();

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			String billNo1 = String.format("YD%s",
					TestDataManager.getRandomNum(10));

			String billNo2 = String.format("YD%s",
					TestDataManager.getRandomNum(10));

			TradingCallService.saveDeliverSummary(orderId, sellerId, billNo1);
			TradingCallService.saveDeliverSummary(orderId, sellerId, billNo2);

			Logger.comment("前置数据准备结束");

			String operateUser = "auto";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("201",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("116",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals(
					String.format("当前订单%s没有运单号",
							rollbackToWaitDeliveryReq.getOrderId()),
					rollbacktowaitdeliveryCall.getString("msg"), "验证msg");
			Logger.verifyEquals(false, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	@Ignore
	public void Tc_RollbackToWaitDelivery_010() {
		Logger.start(true, "订单回滚到待发货,再重新发货成功");
		try {

			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingCallService
					.orderDelivery();
			
			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

			long userId = placeOrderResp.getUserId();

			long tradingId = placeOrderResp.getTradingId();
			
			BigDecimal useAccountAmount = placeOrderResp.getPayableAmount();
			
			TradingCallService.payOrder(userId, useAccountAmount, tradingId);

			TradingCallService.sellerAcceptOrder(sellerId, orderId);
			TradingCallService.delivery(sellerId, orderId, LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);

			Logger.comment("前置数据准备结束");

			String operateUser = "sys";
			String reason = "autotest rollback";

			rollbackToWaitDeliveryReq.setOrderId(orderId);
			rollbackToWaitDeliveryReq.setOperateUser(operateUser);
			rollbackToWaitDeliveryReq.setReason(reason);
			rollbacktowaitdeliveryCall.setData(rollbackToWaitDeliveryReq);
			rollbacktowaitdeliveryCall.callService();

			Logger.verifyEquals("200",
					rollbacktowaitdeliveryCall.getString("code"), "验证code");
			Logger.verifyEquals("0",
					rollbacktowaitdeliveryCall.getString("bcode"), "验证bcode");
			Logger.verifyEquals(true, rollbacktowaitdeliveryCall.getData()
					.getBoolean("success"), "验证success");

			//重新发货
			TradingCallService.delivery(sellerId, orderId, false);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

}